package shop.controller.manage.account;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import shop.core.BaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.common.dao.page.PagerModel;
import shop.services.manage.order.OrderService;
import shop.services.manage.order.bean.Order;
import shop.services.manage.record.RecordService;
import shop.services.manage.record.bean.Record;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;
import shop.services.manage.voucher.VoucherService;
import shop.services.manage.voucher.bean.Voucher;
import shop.services.manage.wallet.WalletService;
import shop.services.manage.wallet.bean.Wallet;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户管理
 * @类名称：AccountAction
 * @创建人：Ltz
 * @创建时间：2017-09-20 下午15:33:04
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/manage/account/")
public class AccountAction extends BaseController<User> {
    private final static String RECORT_TYANSTYPE_CASH = "1";
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AccountAction.class);

    private static final String page_toList = "/manage/user/userList";
    private static final String page_toMyTeam = "/manage/user/mailList";
    private static final String page_toMyOrder = "/manage/order/sellerOrder";
    private static final String page_toMyOrderDetail = "/manage/order/sellerOrderDetail";


    public AccountAction() {
        super.page_toList = page_toList;
        super.page_toAdd = null;
    }


    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private VoucherService voucherService;

    @Override
    public Services<User> getService() {
        return userService;
    }


    /**
     * 跳转到我的团队页面
     *
     * @return
     */
    @RequestMapping("toMyTeam")
    public String toMyTeam() {
        return page_toMyTeam;
    }

    /**
     * 跳转到我的订单列表页面
     *
     * @return
     */
    @RequestMapping("toMyOrder")
    public String toMyOrder() {
        return page_toMyOrder;
    }

    /**
     * 跳转到我的订单详情页面
     *
     * @return
     */
    @RequestMapping("toMyOrderDetail")
    public String toMyOrderDetail(@ModelAttribute("e") Order order, ModelMap model) {
        order = orderService.selectOne(order);
        model.addAttribute("e", order);
        return page_toMyOrderDetail;
    }

    /**
     * 查詢微信用戶信息(列表)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectAccountList")
    @ResponseBody
    public JSONResult selectAllList(User user) throws Exception {
        List<User> userList = userService.selectAccountList(user);
        jsonResult = new JSONResult();
        jsonResult.setData(userList);
        return jsonResult;
    }

    /**
     * 查詢微信用戶信息（详情）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectAccountDetail")
    @ResponseBody
    public JSONResult selectAccountDetail(User user) throws Exception {
        user = userService.selectOne(user);
        if(!"0".equals(user.getPid())){
            User supUser=new User();
            supUser.setId(user.getPid());
            supUser=userService.selectOne(supUser);
            user.setParentName(supUser.getNickname());
        }
        jsonResult = new JSONResult();
        jsonResult.setData(user);
        return jsonResult;
    }

    /**
     * 查詢微信用戶信息
     *
     * @param request 请求
     * @param user       对象参数
     * @return 分页数据模型
     */
    @RequestMapping("selectAccountPage")
    @ResponseBody
    public PagerModel selectAccountPage(HttpServletRequest request, User user) {
        int offset = 0;
        int pageSize = 10;
        int start=Integer.parseInt(request.getParameter("start"));
        int length= Integer.parseInt(request.getParameter("length"));
        if(start>0)
            offset=start;
        if(length>0)
            pageSize=length;
        user.setOffset(offset);
        user.setPageSize(pageSize);
        //查詢微信用戶信息
        PagerModel pager = userService.selectAccountPage(user);
        pager.setRecordsTotal(pager.getTotal());
        pager.setRecordsFiltered(pager.getTotal());
        return pager;
    }

    /**
     * 根据id删除单个上级，并解除与下级的关系
     */
    @RequestMapping(value = "deleteAccount",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteAccount(User e){
        JSONResult jsonResult=new JSONResult();
        userService.delete(e);
        userService.updateJunior(e);
        return jsonResult;
    }

    /**
     * 根据id批量删除微信上级用户,并解除与下级的关系
     */
    @RequestMapping(value = "deleteAccounts",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult deleteAccounts (@RequestParam(value = "ids[]") String[] ids){
        JSONResult jsonResult=new JSONResult();
        User user=new User();
        if (ids == null || ids.length == 0) {
            throw new NullPointerException("请选择需要删除用户！");
        }else {
            for (int i=0;i<ids.length;i++){
                user.setId(ids[i]);
                userService.delete(user);
                userService.updateJunior(user);
            }
        }
        return jsonResult;
    }

    /**
     * 查詢我的团队
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectSubList")
    @ResponseBody
    public JSONResult selectSubList(User user) throws Exception {
        List<User> subUserList = userService.selectSubList(user);
        jsonResult = new JSONResult();
        jsonResult.setData(subUserList);
        return jsonResult;
    }

    /**
     * 查詢我的收益
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectMyIncome")
    @ResponseBody
    public JSONResult selectMyIncome(Record record) throws Exception {
        List<Record> recordList = recordService.selectList(record);
        jsonResult = new JSONResult();
        for(Record recordInfo: recordList){
            if(RECORT_TYANSTYPE_CASH.equals(recordInfo.getTransType())){
                Wallet wallet=new Wallet();
                wallet.setId(recordInfo.getTransID());
                wallet=walletService.selectOne(wallet);
                recordInfo.setCheckStatus(wallet.getStatus());
            }
        }
        jsonResult.setData(recordList);
        return jsonResult;
    }

    /**
     * 查詢我的订单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("selectMyOrder")
    @ResponseBody
    public JSONResult selectMyOrder(Order order) throws Exception {
        List<Order> orderList = orderService.selectMyOrder(order);
        jsonResult = new JSONResult();
        jsonResult.setData(orderList);
        return jsonResult;
    }

}
